import datetime
import json
import pickle
import random
import threading
import time
import warnings

import facade
import requests
from pymongo import MongoClient
from pymongo.errors import DuplicateKeyError
from xjlibrary.configread import MyConfigParser
from xjlibrary.mdatetime.mtime import getTodayDate
from xjlibrary.mdatetime.mtime2 import MDateTimeUtils
from xjlibrary.mrequest.baserequest import USER_AGENTS
from xjlibrary.our_file_dir import BaseDir

curPath = BaseDir.get_file_dir_absolute(__file__)
configfile = BaseDir.get_new_path(curPath, "db.ini")

jpgdir = BaseDir.get_new_path(curPath, "jpg")
BaseDir.create_dir(jpgdir)

class BaseSipo(object):

    def __init__(self, logger=None):
        if not logger:
            self.logger = facade.get_streamlogger()
        else:
            self.logger = logger
        self.Baseurl = "http://202.61.89.133"
        self.domain = "202.61.89.133"
        self.cf = MyConfigParser(configfile).set_keep_keys_case().read_config()
        self.mysqlutils = facade.MysqlUtiles(configfile,
                                             "db",
                                             logger=self.logger)
        self.connection = MongoClient(
            "mongodb://xujiangrw:vipdatacenter@192.168.30.171:27017",
            # 如果“True”且服务器正在运行而没有日志记录，阻塞，直到服务器将所有数据文件同步到磁盘为止。
            fsync=False
        )
        self.db = self.connection['cnipa']
        # 大多数使用的header
        self.header3 = {
            "Accept": "application/json, text/javascript, */*; q=0.01",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Host": self.domain,
            "Origin": self.Baseurl,
            "Proxy-Connection": "keep-alive",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest"
        }

        self.dates417 = {
            "viewQC.viewLiteraQCList[0].srcCnName": "检索式:申请号=(CN200720170285+)",
            "viewQC.viewLiteraQCList[0].srcEnName": "SearchStatement:申请号=(CN200720170285+)",
            "viewQC.viewLiteraQCList[0].searchStrategy": "",
            "viewQC.viewLiteraQCList[0].searchCondition.executableSearchExp": "VDB:(ID='{}')",
            "viewQC.searchKeywords[0]": "[C][ ]{0,}[N][ ]{0,}[2][ ]{0,}[0][ ]{0,}[0][ ]{0,}[7][ ]{0,}[2][ ]{0,}[0][ ]{0,}[1][ ]{0,}[7][ ]{0,}[0][ ]{0,}[2][ ]{0,}[8][ ]{0,}[5][ ]{0,}[ ]{0,}",
            "viewQC.needSearch": "true",
            "viewQC.type": "SEARCH",
            "wee.bizlog.modulelevel": "0200604"
        }

        self.data = {
            "j_loginsuccess_url": "",
            "j_validation_code": "",  # str(code)
            # "wee_remember_me": "on",
            "j_username": "",
            "j_password": ""
        }

        self.check_user_url = self.Baseurl+"/pubsearch/portal/uilogin-checkUserState.shtml"
        self.check_header = {
            "Accept": "application/json, text/javascript, */*; q=0.01",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Host": self.domain,
            "Origin": self.Baseurl,
            "Proxy-Connection": "keep-alive",
            "Referer": self.Baseurl+"/pubsearch/portal/uilogin-forwardLogin.shtml",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest"
        }

    def set_localVal(self, value):
        """
        这个必须调用
        :param value:
        :return:
        """
        self.localVal = value

    def set_user(self, thread_queue, threadval):
        """
        多用户下载 需要设置该进程的用户
        :return:
        """
        # 单线程版
        # row = self.get_user()
        # 多线程版
        threadval.sqlrows = None
        threadval.sqlstat = None
        sql = "select `username`,`j_username`,`j_password`,`isajxupdatetime` from `user` where islogined > -2 and `isajxcount`<5 and stat=1 and `timestat`=%d and url='{}' order by `updatetime` ASC limit 10".format(self.Baseurl)
        sql = sql % threadval.timestat
        thread_queue.put(("user", sql, threadval))
        while threadval.sqlrows is None:
            time.sleep(3)
            if threadval.sqlstat == 0:
                return False
        row = threadval.sqlrows
        self.localVal.userloginname = row[0]
        self.localVal.j_username = row[1]
        self.localVal.j_password = row[2]
        threadval.sqlrows = None
        return True

    def set_ipaddr(self, proxys=None):
        """
        代理不一定是外网地址 比如公司学校代理
        :return:
        """
        # 学校代理版
        # if not proxys:
        #     proxys = self.proxys
        # result = get_ip(proxys)
        # if result:
        #     self.ipaddr = result
        #     self.localVal.ipaddr = result
        #     return True
        # else:
        #     return False
        # 购买代理版
        if not proxys:
            proxys = self.localVal.proxys
        if proxys["http"].find("192.168.30.176") > -1:
            self.localVal.ipaddr = proxys["http"].replace("http://", "").replace("/", "")
        else:
            self.localVal.ipaddr = proxys["http"].split("@")[-1].replace("http://", "").split(":")[0]
        # self.logger.info("ipaddr is {},proxys is {}".format(self.localVal.ipaddr, self.localVal.proxys))
        return True

    def set_proxys(self, proxy, source):
        """
        为请求设置代理
        :param proxy:
        :return:
        """
        if proxy and source:
            if source == "kuaidaili":
                self.localVal.proxy = proxy
                self.localVal.proxys = {
                    "http": "http://%(user)s:%(pwd)s@%(ip)s/" % {'user': "2660438158", 'pwd': "171uz572",
                                                                 'ip': self.localVal.proxy},
                    "https": "http://%(user)s:%(pwd)s@%(ip)s/" % {'user': "2660438158", 'pwd': "171uz572",
                                                                  'ip': self.localVal.proxy}
                }
                return True
            elif source == "mimvp":
                self.localVal.proxy = proxy
                self.localVal.proxys = {
                    "http": "http://%(user)s:%(pwd)s@%(ip)s/" % {'user': "5718b2086b52", 'pwd': "qvyvrcwfvg",
                                                                 'ip': self.localVal.proxy},
                    "https": "http://%(user)s:%(pwd)s@%(ip)s/" % {'user': "5718b2086b52", 'pwd': "qvyvrcwfvg",
                                                                  'ip': self.localVal.proxy}
                }
                return True
            elif source == "school" or source == "other":
                self.localVal.proxy = proxy
                self.localVal.proxys = {
                    "http": "http://%(ip)s/" % {'ip': self.localVal.proxy},
                    "https": "http://%(ip)s/" % {'ip': self.localVal.proxy}
                }
                return True
            else:
                self.logger.info("代理来源无法匹配")
                raise Exception("这个错误不允许存在 必须修复")
        else:
            self.logger.info("传入的代理为 或者代理来源为空")
            return False

    def check_proxys_is_used(self, proxys):
        """
        检查代理是否可以使用
        :param proxys:
        :return:
        """
        url = self.Baseurl+"/pubsearch/patentsearch/searchHomeIndex-searchHomeIndex.shtml"
        header = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Cache-Control": "no-cache",
            "Host": self.domain,
            "Pragma": "no-cache",
            "Proxy-Connection": "keep-alive",
            "Referer": self.Baseurl+"/pubsearch/portal/uilogin-forwardLogin.shtml",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36"
        }
        sn = requests.session()
        self.logger.info(proxys)
        BoolResult, errString, r = facade.BaseRequest(url,
                                                      sn=sn,
                                                      proxies=proxys,
                                                      # mark="欢迎访问专利检索及分析",
                                                      allow_redirects=True,
                                                      headers=header,
                                                      timeout=(20, 60))
        self.logger.info("检查代理有效性 {}".format(errString))
        if BoolResult:
            if r.text.find("您的操作太过频繁，为了不影响系统性能，请稍后再试") > -1:
                self.logger.info("ip can't use ip 被封了" + self.localVal.ipaddr)
                BaseDir.single_write_file(r.text, "./" + str(int(MDateTimeUtils.get_time())) + ".html")
                return "IP"
            if r.text.find("欢迎访问专利检索及分析") > -1:
                return True
            else:
                return False
        else:
            return False

    def check_proxy_post(self, proxys=None):
        """
        检查代理是否可以发送post请求
        :param proxys:
        :return:
        """
        url = "http://httpbin.org/post"
        values = {'a': '1', 'b': '2'}
        BoolResult, errString, r = facade.BaseRequestPost(url,
                                                          data=values,
                                                          endstring="",
                                                          timeout=30)
        if BoolResult:
            return True
        else:
            return False

    def is_login_and_ip(self, sn, proxys, cookie=None):
        """
        判断cookie的有效性
        判断ip是否有效
        :return:
        """
        if cookie:
            sn.cookies.update(cookie)
        url = self.Baseurl+"/pubsearch/patentsearch/searchHomeIndex-searchHomeIndex.shtml"
        header = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Cache-Control": "no-cache",
            "Host": self.domain,
            "Pragma": "no-cache",
            "Proxy-Connection": "keep-alive",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36"
        }
        self.logger.info(proxys)
        # header["X-Forwarded-For"] = self.localVal.ipaddr
        BoolResult, errString, r = facade.BaseRequest(url,
                                                      sn=sn,
                                                      proxies=proxys,
                                                      # mark="退出",
                                                      allow_redirects=True,
                                                      headers=header,
                                                      timeout=(20, 60))
        if BoolResult:
            if r.text.find("请登录") > -1:
                # 登陆失败
                self.logger.info("登陆是失败的，cookie 无效 %s" % proxys)
                return False, "登陆失败"
            elif r.text.find("退出") > -1:
                self.logger.info("登陆是成功的，cookie有效 %s" % proxys)
                return True, "登陆成功"
            else:
                if r.text.find("访问受限") > -1:
                    return False, "访问受限"
                # 登陆成功
                else:
                    self.logger.info("其他情况,请检查")
                    BaseDir.single_write_file(r.text, "./islogin.html")
                    return False, "登陆失败"

        else:
            self.logger.info("检查cookie有效性失败原因是{}".format(errString))
            if errString == "request":
                # 本消息代表IP失效
                return False, "IPInvalid"
            else:
                return False, errString

    def checkLoginTimes(self, username, sn, proxys):
        """
        不使用
        :param username:
        :param sn:
        :param proxys:
        :return:
        """
        url = self.Baseurl+"/pubsearch/portal/checkLoginTimes-check.shtml"
        header = {
            "Accept": "application/json, text/javascript, */*; q=0.01",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Host": self.domain,
            "Origin": self.Baseurl,
            "Pragma": "no-cache",
            "Referer": self.Baseurl+"/pubsearch/portal/uiIndex.shtml",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest"
        }
        data = {
            "username": username
        }
        self.logger.info(self.localVal.proxys)
        # header["X-Forwarded-For"] = self.localVal.ipaddr
        BoolResult, errString, r = facade.BaseRequestPost(url,
                                                          sn=sn,
                                                          proxies=proxys,
                                                          data=data,
                                                          mark="",
                                                          endstring="",
                                                          allow_redirects=True,
                                                          headers=header,
                                                          timeout=(30, 60))
        if BoolResult:
            self.logger.info(r.text)
            # "tips":"0" 目前认为是正常
            # {"tips":"0","username":"qhy_20190226"}
            # 目前知道 "tips":"1" 代表登录失败次数超过6次，帐号锁定，30分钟内不能登录
            # {"tips":"1","username":"xujiang58"}
            return True, ""

        else:
            self.logger.info("检查用户Times失败")
            if r:
                self.logger.info(r.text)
            return False, "请求有误,请检查"

    def login(self, code, sn, proxys, threadval):
        self.data["j_validation_code"] = str(code)
        self.data["j_username"] = self.localVal.j_username
        self.data["j_password"] = self.localVal.j_password
        login_url = self.Baseurl+"/pubsearch/wee/platform/wee_security_check?v={}".format(
            getTodayDate())
        header = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Content-Type": "application/x-www-form-urlencoded",
            "Host": self.domain,
            "Origin": self.Baseurl,
            "Referer": self.Baseurl+"/pubsearch/portal/uilogin-forwardLogin.shtml",
            "Connection": "keep-alive",
            "Upgrade-Insecure-Requests": "1",
            #"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36"
            'User-Agent': random.choice(USER_AGENTS)
        }
        self.logger.info(self.localVal.proxys)
        # header["X-Forwarded-For"] = self.localVal.ipaddr
        BoolResult, errString, r = facade.BaseRequestPost(login_url,
                                                          sn=sn,
                                                          proxies=proxys,
                                                          data=self.data,
                                                          mark="欢迎访问",
                                                          allow_redirects=True,
                                                          headers=header,
                                                          timeout=(20, 30))
        # print()
        try:
            self.logger.info("被重定向的url是：" + r.url)
        except:
            pass
        if BoolResult:

            # self.logger.info("将cookie写入文件")
            # cookiename = self.ipaddr + "_" + str(getTodayDate()) + "_" + self.userloginname + "_login.txt"
            # cookie按外网地址和今天的时间为登陆的cookie文件命名
            # cookiepath = BaseDir.get_new_path(cookiedir, cookiename)
            bytess = pickle.dumps(self.localVal.sn.cookies)
            try:
                create_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
                update_time = MDateTimeUtils.datetime_to_string(
                    MDateTimeUtils.get_minutes_before(MDateTimeUtils.get_now_datetime(), 5), "%Y%m%d%H%M%S")
                if hasattr(threadval, "setstat"):
                    stat = threadval.setstat
                else:
                    stat = 1

                self.logger.info("setstat {}**************************".format(stat))
                self.db.cookies.insert({"user": self.localVal.userloginname,
                                        "ip": self.localVal.ipaddr,
                                        "proxy": self.localVal.proxy,
                                        "cookie": bytess,
                                        "usestat": 0,
                                        "stat": stat,
                                        "origin": "{}".format(self.Baseurl),
                                        "source": threadval.source,
                                        "creattime": create_time,
                                        "searchupdatetime": update_time,
                                        "updatetime": update_time})
            except DuplicateKeyError as e:
                warnings.warn(str(e))
            sql = "update `user` set `islogined`=1 where  `j_username`='{}'".format(self.localVal.j_username)
            threadval.result_queue.put(sql)
            return True, "登陆成功"
        else:
            try:
                if r.url.find("uilogin-forwardLogin.shtml") > -1 or r.url.find("uilogin-loginError.shtml") > -1:
                    sql = "update `user` set islogined=islogined-1 where  `j_username`='{}'".format(
                        self.localVal.j_username)
                    threadval.result_queue.put(sql)
                    return False, "用户有问题"
            except:
                pass
            if errString == "request":
                """
                比如请求超时等
                """
                return False, "IPInvalid"

            boolresult, strings = self.check_user(self.localVal.userloginname, self.localVal.sn, self.localVal.proxys)
            if not boolresult:
                if strings == "failure":
                    sql = "update `user` set stat=-1 where `username`='{}'".format(self.localVal.userloginname)
                    # self.mysqlutils.ExeSqlToDB(sql)
                    threadval.result_queue.put(sql)
                    return False, "用户有问题"
            # if r is not None:
            #     self.logger.info(r.text)
            self.logger.info(self.data)
            self.logger.info(proxys)
            self.logger.info(self.localVal.ipaddr)
            return False, "登陆失败 请查找原因 err:{} 网络错误".format(errString)

    def check_user(self, user, sn, proxys):
        """

        :param user:
        :param sn:
        :param proxys:
        :return:
        """
        postdate = {
            "userName": user
        }
        # self.check_header["X-Forwarded-For"] = self.localVal.ipaddr
        BoolResult, errString, r = facade.BaseRequestPost(self.check_user_url,
                                                          sn=sn,
                                                          data=postdate,
                                                          endstring="",
                                                          headers=self.check_header,
                                                          proxies=proxys,
                                                          timeout=(30, 60)
                                                          )
        if BoolResult:
            try:
                userState = json.loads(r.text)["userState"]
            except:
                self.logger.info("无json返回,认为这是一个正常的用户状态:{}".format(user))
                return True, ""
            if userState == "1":
                # 认为这个状态是账户被封
                self.logger.info("账号失效被封{}".format(user))
                return False, "failure"
            self.logger.info("认为是正常情况,应该为0,状态为{},user为{}".format(userState, user))
            return True, ""
        else:
            self.logger.info("请求出错 无法检查user有效性".format(user))
            return False, "error"

    def set_cookie_from_db(self, updatetime, source, is_time=False, timesleep=150):
        """
        设置cookie 并判断cookie有效性
        :return:
        """
        # 其中1为升序，-1为降序。
        rows = self.db.cookies.find_one({"stat": {"$in": [0, 1]}, "source": source},
                                        {"stat": 1, "cookie": 1, "source": 1, "proxy": 1, "user": 1, "_id": 1,
                                         updatetime: 1},
                                        sort=[(updatetime, 1)])
        if is_time and rows:
            update_time = MDateTimeUtils.datetime_to_string(
                MDateTimeUtils.get_seconds_before(datetime.datetime.utcnow() + datetime.timedelta(hours=8), timesleep),
                "%Y%m%d%H%M%S")
            print(rows[updatetime])
            print(update_time)
            if rows[updatetime] > update_time:
                return False, 20
        if rows:
            update_time = MDateTimeUtils.get_beijin_date_strins()
            self.db.cookies.update({"_id": rows["_id"], "source": rows["source"]},
                                   {"$set": {"stat": rows["stat"],
                                             updatetime: MDateTimeUtils.get_beijin_date_strins()}})
            time.sleep(15)
            rows15s = self.db.cookies.find_one({"_id": rows["_id"]}, {updatetime: 1})
            if rows15s[updatetime] != update_time:
                return False, "cookie 被占用 重新获取"
            self.logger.info("获取一个代理{}".format(rows["proxy"]))
            bytess = rows["cookie"]
            if not self.set_proxys(rows["proxy"], rows["source"]):
                self.db.cookies.update({"_id": rows["_id"], "source": rows["source"]},
                                       {"$set": {"stat": rows["stat"],
                                                 updatetime: MDateTimeUtils.get_beijin_date_strins()}})
                return False, "代理为空"
            self.localVal.sn = requests.session()
            self.localVal.cookies = pickle.loads(bytess)
            # print(self.cookie)
            self.localVal.sn.cookies.update(self.localVal.cookies)
            self.db.cookies.update({"_id": rows["_id"], "source": rows["source"]},
                                   {"$set": {updatetime: MDateTimeUtils.get_beijin_date_strins()}})
            return True, rows
            # if not self.set_ipaddr():
            #     self.localVal.ipaddr = "192.168.30.176"
            #     self.logger.info("获取ip地址无效 检查ip是否有效")
            #     # return False, "获取ip地址无效 检查ip是否有效"
            # boolresult, msg = self.is_login_and_ip(self.sn, self.proxys, self.cookie)
            # if boolresult:
            #     self.db.cookies.update({"_id": rows["_id"]},
            #                            {"$set": {updatetime:MDateTimeUtils.get_beijin_date_strins()}})
            #     return True, rows
            # else:
            #     self.db.cookies.update({"_id": rows["_id"]},
            #                            {"$set": {"stat": 0, updatetime: MDateTimeUtils.get_beijin_date_strins()}})
            #     return False, "cookies无效"
        else:
            return False, "cookie表为空"

    def down_search_page(self, sn, proxys):
        """
        获取ip请求 该请求在搜索请求前，否则搜索请求不会成功
        :return:
        """
        #url = self.Baseurl+"/pubsearch/patentsearch/pageIsUesd-pageUsed.shtml"
        url = self.Baseurl+"/pubsearch/patentsearch/preExecuteSearch!preExecuteSearch.do"
        # self.header3["X-Forwarded-For"] = self.localVal.ipaddr
        BoolResult, errString, r = facade.BaseRequestPost(url,
                                                          sn=sn,
                                                          proxies=proxys,
                                                          endstring="",
                                                          mark="IP",
                                                          allow_redirects=True,
                                                          headers=self.header3,
                                                          timeout=(30, 60))
        if BoolResult:
            self.logger.info("搜索前获取ip成功 %s" % proxys)
            return True
        else:
            self.logger.info("搜索前获取ip失败 %s;errString:%s" % (proxys, errString))
            return False

    def search_detail(self, sn, proxys):
        """
        发现当遭遇417错误时 调用search可能会解决417错误
        :return:
        """
        header = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Content-Type": "application/x-www-form-urlencoded",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Pragma": "no-cache",
            "Host": self.domain,
            "Origin": self.Baseurl,
            "Referer": self.Baseurl+"/pubsearch/patentsearch/tableSearch-showTableSearchIndex.shtml",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",

        }

        url = self.Baseurl+"/pubsearch/patentsearch/showViewList-jumpToView.shtml"
        # header["X-Forwarded-For"] = self.localVal.ipaddr
        BoolResult, errString, r = facade.BaseRequestPost(url,
                                                          sn=sn,
                                                          headers=header,
                                                          proxies=proxys,
                                                          data=self.dates417,
                                                          endstring="",
                                                          allow_redirects=True,
                                                          mark="",
                                                          timeout=(30, 60))
        if BoolResult:
            self.logger.info("解决417问题 %s" % proxys)
            return True, r
        else:
            self.logger.info("解决417问题失败 %s" % proxys)
            return False, r


    def get_verification_code(self):
        """
        获取验证码保存到文件
        :return:
        """
        url = self.Baseurl+"/pubsearch/portal/paramRewriter-paramEncode.shtml"
        data = {
            "params": "d={}".format(str(int(time.time())))
        }
        headers = {
            "Accept": "application/json, text/javascript, */*; q=0.01",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Origin": self.Baseurl,
            "Referer": self.Baseurl+"/pubsearch/portal/uilogin-forwardLogin.shtml",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest"
        }
        BoolResult, errString, r = facade.BaseRequestPost(url,
                                                          sn=self.localVal.sn,
                                                          data=data,
                                                          proxies=self.localVal.proxys,
                                                          headers=headers,
                                                          mark="params",
                                                          endstring="",
                                                          timeout=(30, 60))
        if BoolResult:
            params = json.loads(r.text)["params"]
        else:
            self.logger.info("获取验证码前获取的参数错误")
            return False

        verification_code_url = self.Baseurl+"/pubsearch/portal/login-showPic.shtml?" + params
        imageheader = {
            "Referer": self.Baseurl+"/pubsearch/portal/uilogin-forwardLogin.shtml",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36"
        }
        self.logger.info(self.localVal.proxys)
        # imageheader["X-Forwarded-For"] = self.localVal.ipaddr
        # 下载验证码图片
        BoolResult, errString, r = facade.BaseRequest(verification_code_url,
                                                      sn=self.localVal.sn,
                                                      proxies=self.localVal.proxys,
                                                      headers=imageheader,
                                                      endstring="",
                                                      timeout=(30, 60))
        if BoolResult:
            if r.text.find("访问受限") > -1:
                self.logger.info("ip can't use ip 被封了" + self.localVal.ipaddr + ":" + self.localVal.userloginname)
                return "IP"
            jpgpath = BaseDir.get_new_path(jpgdir, "login_" + str(threading.get_ident()) + ".jpg")
            jpgpath = jpgpath.encode('utf-8')
            self.logger.info("login verification code save in %s" % jpgpath)
            BaseDir.single_write_wb_file(r.content, jpgpath)
            return jpgpath
        else:
            return False
